import { profileAPI } from "@/api/userApi";

// 初始的 state 对象
let initState = {
  tokenInfo: {},
  profile: {},
  myCity: "",
  watchingUser: {},
};
const stateStr = localStorage.getItem("xunshi_state");
if (stateStr) {
  // 加载本地的数据
  initState = JSON.parse(stateStr);
}
export default {
  namespaced: true,
  state: initState,
  mutations: {
    updateTokenInfo(state, payload) {
      state.tokenInfo = payload;
      if (!payload.token) {
        this.commit("user/cleanState");
        return;
      }
      this.commit("user/saveStateToStorage");
    },
    updateUserInfo(state, payload) {
      state.profile = payload.user;
      this.commit("user/saveStateToStorage");
    },
    updateMyCity(state, payload) {
      state.myCity = payload;
    },
    updateWatchingUser(state, payload) {
      state.watchingUser = payload;
    },
    saveStateToStorage(state) {
      localStorage.setItem("xunshi_state", JSON.stringify(state));
    },
    cleanState(state) {
      // 1. 清空 vuex 中的数据
      state.tokenInfo = {};
      state.profile = {};
      state.watchingUser = {};
      // 2. 将清空后的 state 存储到本地
      this.commit("user/saveStateToStorage");
    },
  },
  actions: {
    async initProfile(ctx) {
      const { data: res } = await profileAPI(ctx.state.tokenInfo.user_id);
      ctx.commit("updateUserInfo", { user: res });
      ctx.commit("updateWatchingUser", res);
    },

    async initWatchingUser({ commit }, user_id) {
      const { data: res } = await profileAPI(user_id);
      commit("updateWatchingUser", res);
    },
  },
};
